package com.tang.juc.aqs;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * @author tlm
 * @version 1.0
 * @date 2020/4/22 21:46
 * 手写同步器实现秒杀场景
 */
@Slf4j
@RestController
//@RequestMapping("/user")
@Api(value = "手写同步器实现秒杀场景", tags = {"手写同步器实现秒杀场景"})
public class SpikeDemo {
    CustomLock customLock = new CustomLock();
    @Autowired
    JdbcTemplate jdbcTemplate;



    @PostMapping("/Spike/desStock")
    @ApiOperation(value = "秒杀减库存")
    public String desStock(){
        customLock.lock();
        Integer stock;
       List<Map<String,Object>> result = jdbcTemplate.queryForList("SELECT stock FROM shop_stock WHERE id = 77");
       if(result==null || result.isEmpty() ||(stock=(Integer) result.get(0).get("stock"))<=0){
           log.info("下单失败，已经没有库存了！");
           customLock.unlock();
           return "下单失败，已经没有库存了！";
        }
       stock--;
       jdbcTemplate.update("update shop_stock set stock=? where id = 77",stock);
       log.info("下单成功，当前剩余库存为："+stock);

       customLock.unlock();
        return "下单成功，当前商品剩余库存为："+stock;
    }
}
